<?php
class UserManager extends CI_Model {
	function __construct() {
		parent::__construct ();
		$this->load->database ();
	}
	
	function checkLogin($loginName, $pwd) {
		$this->db->where ( "user_login_name", $loginName );
		$query = $this->db->get ( 'cpy_user' );
		
		if ($query->num_rows () <= 0)
			return FALSE;
		foreach ( $query->result () as $result ) {
			if (strcasecmp ( $pwd, $result->user_pwd ) == 0) {
				$this->takeLoginTime ( $result->cpy_user_id );
				$query->free_result ();
				return TRUE;
			} else {
				$query->free_result ();
				return FALSE;
			}
		}
		$query->free_result ();
		return FALSE;
	}
	
	function takeLoginTime($userId) {
		$this->db->where ( 'cpy_user_id', $userId );
		$query = $this->db->get ( 'cpy_user' );
		
		if ($query->num_rows () == 1) {
			foreach ( $query->result () as $result ) {
				$loginTimes = $result->user_logined_cnt;
				
				$data ['user_logined_cnt'] = $loginTimes + 1;
				date_default_timezone_set ( 'PRC' );
				$data ['user_last_time'] = date ( "y-m-d H:i:s" );
				
				$this->db->where ( 'cpy_user_id', $userId );
				$this->db->update ( 'cpy_user', $data );
			}
		}
	}
	
	function getUserObj($loginName) {
		$this->db->where ( "user_login_name", $loginName );
		$query = $this->db->get ( 'cpy_user' );
		if ($query->num_rows () <= 0)
			return NULL;
		
		$data = array ();
		foreach ( $query->result () as $result ) {
			$data ['userId'] = $result->cpy_user_id;
			$data ['cpyId'] = $result->cpy_id;
			$data ['userName'] = $result->user_name;
			$data ['lastLogined'] = $result->user_last_time;
			$data ['loginedCnt'] = $result->user_logined_cnt;
		}
		$query->free_result ();
		return $data;
	}
}

?>